using System;
using System.IO;
using System.Xml.Serialization;

namespace ProxyServer.ProxyImpl
{
    [Serializable]
    public class ProxyConfig
    {
        private string host;
        private int port;
        private string proxyHost;
        private int proxyPort;
        private string proxyUser;
        private string proxyPass;

        public string Host
        {
            get { return host; }
            set { host = value; }
        }

        public int Port
        {
            get { return port; }
            set { port = value; }
        }

        public string ProxyHost
        {
            get { return proxyHost; }
            set { proxyHost = value; }
        }

        public int ProxyPort
        {
            get { return proxyPort; }
            set { proxyPort = value; }
        }

        public string ProxyUser
        {
            get { return proxyUser; }
            set { proxyUser = value; }
        }

        public string ProxyPass
        {
            get { return proxyPass; }
            set { proxyPass = value; }
        }
    }

    public class ProxyConfigManager
    {
        private const string ConfigFile = "proxy.xml";

        private static ProxyConfig config;

        public static ProxyConfig ReadSetting()
        {
            if (config == null)
            {
                if (File.Exists(ConfigFile))
                {
                    var serializer = new XmlSerializer(typeof(ProxyConfig));

                    using (var sr = new StreamReader(ConfigFile))
                    {
                        config = (ProxyConfig)serializer.Deserialize(sr);
                        sr.Close();
                    }
                }
                else
                {
                    config = new ProxyConfig();
                }
            }

            return config;
        }

        public static void SaveSettings(ProxyConfig proxyConfig)
        {
            if (proxyConfig != null)
            {
                var serializer = new XmlSerializer(typeof(ProxyConfig));

                using (var sw = new StreamWriter(ConfigFile))
                {
                    serializer.Serialize(sw, proxyConfig);
                    sw.Close();
                }

                config = proxyConfig;
            }
        }
    }
}